package com.tpp.gateway.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import com.tpp.comm.util.JwtUtil;
import com.tpp.comm.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class TppFilter implements GlobalFilter, Ordered {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //用于返回错误提示信息的方法
    @SneakyThrows
    private Mono<Void> executeResult(ServerHttpResponse resp, Result result) {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        DataBuffer dataBuffer =  resp.bufferFactory().wrap(bytes);

        Mono<Void> voidMono = resp.writeWith(Mono.just(dataBuffer));
        return voidMono;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().getPath();
        if(uri.contains("/p/")){
            return chain.filter(exchange);
        }else if(uri.contains("/v/")) {
            String token = request.getHeaders().getFirst("token");
            if(StringUtils.isEmpty(token)){
                Result result = Result.noLogin("token不存在");
                return this.executeResult(response,result);
            }
            int id = jwtUtil.parseJwt(token);
            String tokenKey = "tppd13:token:"+Math.abs(id);
            Boolean flag = stringRedisTemplate.hasKey(tokenKey);
            if(id>0){ //当前请求时间点小于token有效期（20分钟）
                return chain.filter(exchange);
            } else if(id==0){//无效token(有可能是伪造的)
                Result result = Result.fail("token为伪造token");
                return this.executeResult(response,result);
            } else if (flag) {//分两种情况 1.超过20分钟，但非活动时间没有过期
                BoundValueOperations<String, String> ops = stringRedisTemplate.boundValueOps(tokenKey);
                String newTokwn=jwtUtil.createJwt(Math.abs(id));
                ops.set(newTokwn,jwtUtil.getExpTime()*2, TimeUnit.MINUTES);

                ServerHttpRequest host = exchange.getRequest().mutate().header("token", newTokwn).build();
                ServerWebExchange build = exchange.mutate().request(host).build();
                return chain.filter(build);
            } else {//2.token过期超过非活动时间40分钟
                Result result = Result.fail("token超时");
                return this.executeResult(response,result);
            }
        }else if(uri.contains("/s/")){
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
